package vn.personal.anhht.bloback12.activity;

import java.util.ArrayList;

import vn.personal.anhht.bloback12.adapter.LogItemAdapter;
import vn.personal.anhht.bloback12.bean.LogObject;
import vn.personal.anhht.bloback12.database.CallBlockDatabaseCallsBlockAdapter;
import vn.personal.anhht.bloback12.widget.ActionBar;
import vn.personal.anhht.bloback12.widget.ActionBar.Action;
import vn.personal.anhht.bloback12.widget.ActionBar.IntentAction;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class LogCallActivity extends Activity{

	private LogItemAdapter adapterLog;
	private ListView lvLogs;
	private ArrayList<LogObject> listCallLog = new ArrayList<LogObject>();
	ProgressDialog dialog;
	CallBlockDatabaseCallsBlockAdapter callsBlockAdapter;
	private Resources rs;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab_log_call);
		rs = getResources();
		
		final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
        actionBar.setTitle("Block Calls");
		final Action helpAction = new IntentAction(this, createShareIntent(),
                R.drawable.ic_action_help);
        actionBar.addAction(helpAction);
        final Action otherAction = new IntentAction(this, new Intent(this,
                SettingActivity.class), R.drawable.ic_action_settings);
        actionBar.addAction(otherAction);
        actionBar.setHomeAction(new IntentAction(this, HomeActivity.createIntent(this), R.drawable.ic_action_home_default));
        actionBar.setDisplayHomeAsUpEnabled(true);
		Log.e("LOGCALL TAB", "LOGCALL TAB");
		
		initLogCall();
	}
	
	private Intent createShareIntent() {
        final Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, "Shared from the ActionBar widget.");
        return Intent.createChooser(intent, "Share");
    }
	
	public void initLogCall(){
		dialog = new ProgressDialog(this);
		lvLogs = (ListView) findViewById(R.id.lvcalllog);
		lvLogs.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                displayDialog(arg2);
                return false;
            }
        });
		adapterLog = new LogItemAdapter(getApplicationContext(),
				android.R.layout.simple_list_item_1, listCallLog);
		new GetLogThread().execute();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.mn_filter, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.item_filter_clear: {
		    final AlertDialog.Builder alert = new AlertDialog.Builder(this);
	        alert.setTitle(getResources().getString(R.string.history_alert_title));
	        alert.setMessage(getResources().getString(R.string.history_alert_msg));
	        alert.setPositiveButton(getResources().getString(R.string.ok) , new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {
	                deleteLogCall();
	                Toast.makeText(getApplicationContext(), getResources().getString(R.string.history_toast_delok),
	                        Toast.LENGTH_LONG).show();
	                refresh();
	            }
	        });

	        alert.setNegativeButton(getResources().getString(R.string.cancel),
	                new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                        dialog.cancel();
	                    }
	                });
	        alert.show();
			break;
		}
		case R.id.item_filter_back:
		    back(RESULT_OK);
            break;
		default:
			super.onOptionsItemSelected(item);
		}
		return true;
	}

	public void refresh() {
		listCallLog.clear();
		new GetLogThread().execute();
	}
	
	public void displayDialog(final int position){
        final LogObject callLog = listCallLog.get(position);
        final AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle(rs.getString(R.string.history_alert_title));
        alert.setMessage(rs.getString(R.string.history_alert_call));
        alert.setPositiveButton(rs.getString(R.string.remove), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                callsBlockAdapter.open();
                callsBlockAdapter.deleteCallsBlock(Integer.parseInt(callLog.getId()));
                callsBlockAdapter.close();
                Toast.makeText(getApplicationContext(), rs.getString(R.string.delete),
                        Toast.LENGTH_LONG).show();
                refresh();
            }
        });
        alert.setNegativeButton(rs.getString(R.string.cancel),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                });
        alert.show();
    }
	
	public void deleteLogCall() {
	    callsBlockAdapter.open();
	    callsBlockAdapter.deleteAll();
	    callsBlockAdapter.close();
	}
	
	/* ========================Get List Log============================= */
	public class GetLogThread extends
			AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... params) {
			queryCallIncomed();
			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.setMessage(rs.getString(R.string.bl_dialog_load));
			dialog.show();
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			lvLogs.setAdapter(adapterLog);
		}
		
		private void queryCallIncomed() {
			
		    callsBlockAdapter = new CallBlockDatabaseCallsBlockAdapter(getApplicationContext());
		    callsBlockAdapter.open();
		    Cursor callCursor = callsBlockAdapter.selectAllCallsBlock();
			if (callCursor.moveToFirst()) {
				String mynumber = null;
				String myname = null;
				String mytype = null;
				String mydate = null;
				String myid = null;
				int indexOfNumber = callCursor.getColumnIndex(CallBlockDatabaseCallsBlockAdapter.KEY_PHONE);
				int indexOfCachedName = callCursor.getColumnIndex(CallBlockDatabaseCallsBlockAdapter.KEY_NAME);
				int indexOfDateCall = callCursor.getColumnIndex(CallBlockDatabaseCallsBlockAdapter.KEY_TIME);
				int indexOfTypeCall = callCursor.getColumnIndex(CallBlockDatabaseCallsBlockAdapter.KEY_TYPE);
				int indexOfId = callCursor.getColumnIndex(CallBlockDatabaseCallsBlockAdapter.KEY_ID);
				do {
					LogObject lo = new LogObject();
					mynumber = callCursor.getString(indexOfNumber);
					if (mynumber == null) {
						lo.setPhone(rs.getString(R.string.pick_string_nophone));
					} else {
						lo.setPhone(mynumber);
					}
					myname = callCursor.getString(indexOfCachedName);
					if (myname == null) {
						lo.setName(rs.getString(R.string.pick_string_noname));
					} else {
						lo.setName(myname);
					}
					mydate = callCursor.getString(indexOfDateCall);
					lo.setTime(mydate);
					mytype = callCursor.getString(indexOfTypeCall);
					lo.setType(Integer.parseInt(mytype.trim()));
					myid = callCursor.getString(indexOfId);
					lo.setId(myid);
					listCallLog.add(lo);
				} while (callCursor.moveToNext());
			}
			callCursor.close();
			callsBlockAdapter.close();
		}
	}
	
	public void back(int resultCode) {

        Intent replyIntent = new Intent();
        setResult(resultCode, replyIntent);
        finish();
    }
}
